<template>
  <div>
    <div class="box">
      <input v-model="valueText" class="box-input" type="text" placeholder="输入城市名或拼音">
    </div>

    <div class="serch-content" ref="serch" v-show="valueText">     
      <ul>
        <li class="serch-item" v-for="item in list" @click="handleCityClick(item.name)" :key="item.id">{{item.name}}</li>
        <li class="serch-item" v-show="!list.length">没有找到匹配的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
// vuex
import {mapState, mapActions} from "vuex";
// 滚动-插件
import BScroll from '@better-scroll/core';

export default {
  name: "search",
  props: ["cities"],
  data() {
    return {
      valueText: "",
      list: [],
      times: null,
      
      scroll: null,
    }
  },
  watch: {
    valueText() {
      if(this.times) {
        clearTimeout(this.times);
      }
      if(this.valueText == '') {
        this.list = [];
        return ;
      }

      this.times = setTimeout(() => {
        for(let key in this.cities) {
          for(let value of this.cities[key]) {
            if(value.spell.indexOf(this.valueText) != -1 || value.name.indexOf(this.valueText) != -1) {          
              this.list.push(value);
            }
          }
        }  
      }, 100);          
    }
  },
  methods: {
    // 点击城市 actions
    ...mapActions({changecity: "changecity"}),

    handleCityClick(name) {      
      this.$store.dispatch("changecity", name);

      this.changecity(name);      
      this.$router.push("/");
    }
  },

  mounted() {
    // 滚动-插件-使用
    const options = {
      click: true,
      tap: true,
    }
    this.scroll = new BScroll(this.$refs.serch, options);
  },
  updated() {
    // 数据产生更新导致无法生成滚动条，因为并被解析当前数据所占用的空间需要重新调用该实例重新计算
    this.scroll.refresh();
  }
}
</script>

<style scoped>
  .box {
    height: 36px;
    padding: 0px 5px;
    background-color: #00bcd4;
  }
  .box .box-input {
    width: 100%;
    height: 31px;
    padding: 0px 5px;
    line-height: 31px;
    text-align: center;
    border-radius: 3px;
    color: #666;

    box-sizing: border-box;
  }

  /* 搜索显示框 */
  .serch-content {
    position: absolute;
    z-index: 2;

    top: 79px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background-color: #eee;

    overflow: hidden;
  }
  .serch-content .serch-item {
    line-height: 31px;
    padding-left: 5px;
    color: #666;

    background-color: #fff;
  }
</style>